#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#define MAX_LINE_LEN 512
#define FLAG_DELAY 0xFD

// 处理GEN_WR命令
void process_genwr(FILE *out, const char *params) {
    char buf[MAX_LINE_LEN];
    char *args[20];
    int arg_count = 0;
    
    // 分割参数
    strncpy(buf, params, MAX_LINE_LEN);
    char *token = strtok(buf, ",");
    
    while (token != NULL && arg_count < 20) {
        // 去除空格
        while (isspace(*token)) token++;
        if (*token != '\0') {
            args[arg_count++] = token;
        }
        token = strtok(NULL, ",");
    }

    if (arg_count == 0) return;

    // 写入寄存器地址
    fprintf(out, "    %s, %d", args[0], arg_count-1);
    
    // 写入参数
    for (int i = 1; i < arg_count; i++) {
        fprintf(out, ", %s", args[i]);
    }
    fprintf(out, ",\n");
}

// 处理延时命令
void process_delay(FILE *out, int ms) {
    fprintf(out, "    ,FLAG_DELAY,FLAG_DELAY, %d,\n", ms);
}

int main(int argc, char *argv[]) {
    FILE *fin, *fout;
    char line[MAX_LINE_LEN];
    int delay_val;
    const char *input_file = "input.txt";
    const char *output_file = "output.c";

    // 检查命令行参数，若有提供则替换默认文件名
    if (argc >= 2) {
        input_file = argv[1];
    }
    if (argc >= 3) {
        output_file = argv[2];
    }

    if ((fin = fopen(input_file, "r")) == NULL) {
        perror("Error opening input file");
        return EXIT_FAILURE;
    }

    if ((fout = fopen(output_file, "w")) == NULL) {
        perror("Error opening output file");
        fclose(fin);
        return EXIT_FAILURE;
    }

    // 写入文件头
    fprintf(fout, "// Auto-generated initialization code\n");
    fprintf(fout, "const unsigned char init_code_array[] = {\n");

    while (fgets(line, MAX_LINE_LEN, fin)) {
        // 清理行内容
        char *comment = strchr(line, '/');
        if (comment) *comment = '\0';
        
        // 跳过空行和非相关命令
        if (strstr(line, "FPGA_INI") || 
            strstr(line, "writedata") ||
            strstr(line, "writecomm") ||
            strlen(line) < 5) continue;

        // 处理GEN_WR命令
        if (strstr(line, "GEN_WR")) {
            char *start = strchr(line, '(');
            char *end = strchr(line, ')');
            if (start && end) {
                *end = '\0';
                process_genwr(fout, start+1);
            }
        }
        // 处理延时命令
        else if (strstr(line, "delayms_pc")) {
            if (sscanf(line, "delayms_pc(%d);", &delay_val) == 1) {
                process_delay(fout, delay_val);
            }
        }
    }

    // 写入文件尾
    fprintf(fout, "};\n");

    fclose(fin);
    fclose(fout);
    printf("Conversion completed successfully.\n");
    return EXIT_SUCCESS;
}
